import React, {FC, useEffect, useRef, useState} from "react";
import {WebviewConfig} from "@type/webview.ts"
import styled from "styled-components";
import clsx from "clsx";
import {Select, SelectProps} from "antd";
import qs from 'qs'

const ipcRender = window.ipcRenderer

// const ETabItem: FC<{
//     props: { id?: number; text?: string; name?: string; content?: string; },
//     className?: string
// }> = ({props, className}) => {
//     const {text}=props
//     return (
//         <TabItem className={className}>{text}</TabItem>
//     );
// };
const TabList=styled.div`
    display: flex;
    align-items: center;
    padding-top: 5px;
    background-color: #57AAB4;
    .tab_item {
        min-width: 150px;
        max-width: 300px;
        height: 40px;
        display: flex;
        align-items: center;
        padding: 0 10px;
        position: relative;
        overflow: hidden;
        padding-right: 40px;
        &::after{
            content: "|";
            position: absolute;
            right: 0px;
        }
        &:last-child {
            &::after {
                content: ""; 
            }
        }
        &.active {
            --tab-color: pink;
            /* 弧度半径 */
            --r: 14px;
            /* tab 背景 */
            --bg: linear-gradient(to right, red, blue) border-box;
            /* 边框遮罩 */
            --mask: radial-gradient(var(--r) at var(--r) 0, rgba(208, 49, 145, 0) 100%, var(--tab-color) 100%) calc(-1 * var(--r)) 100%/100% var(--r) repeat-x,
            linear-gradient(var(--tab-color), var(--tab-color)) padding-box;
            padding-inline: var(--r);
            background: var(--bg);
            place-content: center;
            font-size: 16px;
            font-weight: bold;
            color: #fff;
            /* 靠border延伸出背景色，这里border设置透明也行，设置tab背景色也行，但是设置透明可以就不用后续调整了 */
            border-left: var(--r) solid #0000;
            border-right: var(--r) solid #0000;
            /* 给 border-radius 让padding-box上边具有弧度 */
            border-radius: calc(2 * var(--r)) calc(2 * var(--r)) 0 0/var(--r);
            mask: var(--mask);
            -webkit-mask: var(--mask);
            padding-right: 40px;
            &::after{
                content: "";
            }
        }
        .close_btn_icon{
            position: absolute;
            right: 6px;
            font-size: 10px;
            width: 14px;
            height: 14px;
            line-height: 14px;
            text-align: center;
            &:hover{
                background-color: blueviolet;
            }
        }
        .avatar_img{
            margin-right: 10px;
        }
    }
`
const inputStyles: React.CSSProperties = {
    'width':'100%'
};

const Home: FC = () => {
    const webviewRef = useRef(null);
    const [currentActive,setCurrentActive]=useState(0)
    const [webviewConfig, setWebviewConfig] = useState<WebviewConfig>({
        width: 200,
        height: 300,
        code: "baijia",
        title: "百家号",
        url: "https://baijiahao.baidu.com/builder/theme/bjh/login",
        x: 0,
        y: 0
    })
    const tabs = [
        {id: 1, text: "Tab 1", name: "Tab 1", content: "内容1"},
        {id: 2, text: "Tab 2", name: "Tab 1", content: "内容1"},
        {id: 3, text: "Tab 3", name: "Tab 1", content: "内容1"},
        {id: 4, text: "Tab 4", name: "Tab 1", content: "内容1"},
        {id: 5, text: "Tab 5", name: "Tab 1", content: "内容1"},
        {id: 6, text: "Tab 6", name: "Tab 1", content: "内容1"},
    ]
    const handleTabChange = (item:any,index: number) => {
        setCurrentActive(index)
        console.log('Changed selected tab to:', item,index)
        console.log(webviewConfig,333333333)
        ipcRender.send("create-new-webview", webviewConfig)
    }
    useEffect(() => {
        if (webviewRef.current) {
            // 获取 Webview 元素的位置信息和大小
            const rect = webviewRef.current.getBoundingClientRect();
            setWebviewConfig((prevState) => {
                return {...prevState, x: rect.x, y: rect.y, width: rect.width, height: rect.height};
            });
        }
    },[])
    window.addEventListener("resize",()=>{
        const rect = webviewRef.current.getBoundingClientRect();
        setWebviewConfig((prevState) => {
            return {...prevState, x: rect.x, y: rect.y, width: rect.width, height: rect.height};
        });
    })
    return (
        <div className="flex h-full">
            <div className="bg-[#e8e6e2ff] w-[170px] tt-themColor">
                <SearchInput placeholder="请选择账号" style={inputStyles}></SearchInput>
            </div>
            <div className="flex-1 flex flex-col h-full">
                <TabList>
                    {
                        tabs.map((item,index:number)=>{
                            return (
                                <div className={clsx('tab_item',{'active':index===currentActive})} onClick={()=>{handleTabChange(item,index)}} key={index}>
                                    <div className='avatar_img'><span className='iconfont icon-shuaxin'></span></div>
                                    <div>百家号-爱吃老虎</div>
                                    <span className='iconfont icon-guanbi close_btn_icon rounded-full' onClick={()=>{}}></span>
                                </div>
                            )
                        })
                    }
                </TabList>
                <div className='h-[44px] flex items-center px-4 gradient-nav-bg-color'>
                    <div className='flex-1 space-x-4 flex items-center'>
                        <span className='iconfont icon-zhixiangzuo'></span>
                        <span className='iconfont icon-zhixiangyou'></span>
                        <span className='iconfont icon-shuaxin'></span>
                        <span className='iconfont icon-shoucang'></span>
                        <span className='border-amber border-solid border-1 py-1 px-4 rounded-2xl flex-1 bg-[#57AAB4]'>https://gitee.com/zhang_erdan/electron_react_demo</span>
                    </div>
                </div>
                <div ref={webviewRef} style={{height: 'calc(100% - 130px)'}}
                     className='w-full bg-blue'>22222222
                </div>
            </div>
        </div>
    );
};


export default Home;





let timeout: ReturnType<typeof setTimeout> | null;
let currentValue: string;

const fetchInput = (value: string, callback: (data: { value: string; text: string }[]) => void) => {
    if (timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    currentValue = value;

    const fake = () => {
        const str = qs.stringify({
            code: 'utf-8',
            q: value,
        });
        fetch(`https://suggest.taobao.com/sug?${str}`)
            .then((response: unknown) => response.json())
            .then((d: unknown) => {
                if (currentValue === value) {
                    const { result } = d;
                    const data = result.map((item: unknown) => ({
                        value: item[0],
                        text: item[0],
                    }));
                    callback(data);
                }
            });
    };
    if (value) {
        timeout = setTimeout(fake, 300);
    } else {
        callback([]);
    }
};

const SearchInput: React.FC<{ placeholder: string; style: React.CSSProperties }> = (props) => {
    const [data, setData] = useState<SelectProps['options']>([]);
    const [value, setValue] = useState<string>();

    const handleSearch = (newValue: string) => {
        fetchInput(newValue, setData);
    };

    const handleChange = (newValue: string) => {
        setValue(newValue);
    };

    return (
        <Select
            showSearch
            value={value}
            placeholder={props.placeholder}
            style={props.style}
            defaultActiveFirstOption={false}
            suffixIcon={null}
            filterOption={false}
            onSearch={handleSearch}
            onChange={handleChange}
            notFoundContent={null}
            options={(data || []).map((d) => ({
                value: d.value,
                label: d.text,
            }))}
        />
    );
};
